<?php
class Mysql
{
	var $conn;
	var $db_host;
	var $db_port;
	var $db_user;
	var $db_password;
	var $db_database;
	var $db_charset;
	var $p_connect;
	var $is_debug;
	var $query_num;
	var $start_time;
	var $query_sql;
	function Mysql($db_host, $db_port = '3306', $db_user = 'root', $db_password = '', $db_database = '',$db_charset = 'latin1', $p_connect = 0, $debug = false)
	{
		$this->start_time = microtime(1);
		$this->query_num = 0;
		$this->db_host=$db_host;
		$this->db_port=$db_port;
		$this->db_user=$db_user;
		$this->db_password=$db_password;
		$this->db_database=$db_database;
		$this->db_charset=$db_charset;
		$this->p_connect=$p_connect;
		$this->is_debug=$debug;
		$this->conn = $this->connect();
		$this->set_charset();
		$this->select_db();
		$this->connect_time = microtime(1) - $this->start_time;
	}
	function connect()
	{
		if(!$this->conn)
		{
			$conn = false;
			if($this->p_connect)
			{
				$conn = mysql_pconnect($this->db_host.':'.$this->db_port, $this->db_user, $this->db_password);
			}
			if(!$conn) 
			{
				$conn = mysql_connect($this->db_host.':'.$this->db_port, $this->db_user, $this->db_password,true);
			}
			if($conn)
			{
				unset($this->db_host);
				unset($this->db_password);
				unset($this->db_user);
				return $conn;
			}
			else 
			{
				$this->print_err(mysql_error());
			}
		}
		return $this->conn;
	}
	function select_db()
	{
		if(!$this->conn)
		{
			$this->connect();
		}
		if($this->conn)
		{
			return mysql_select_db($this->db_database,$this->conn);
		}
	}
	function set_charset()
	{
		if(!$this->conn)
		{
			$this->connect();
		}
		$version = mysql_get_server_info($this->conn);
        /* 如果mysql 版本是 4.1+ 以上，需要对字符集进行初始化 */
        if ($version > '4.1')
        {
            if ($this->db_charset != 'latin1')
            {
                mysql_query("SET character_set_connection='{$this->db_charset}', character_set_results='{$this->db_charset}', character_set_client=binary", $this->conn);
            }
            if ($version > '5.0.1')
            {
                mysql_query("SET sql_mode=''", $this->conn);
            }
        }
	}
	function query($sql)
	{
		@new ActionLog(array("LogType"=>"querylog","Action"=>"|||||\t$sql\t|||||\t{$currAdmin->AID}"));
		if(!$this->conn)
		{
			$this->connect();
		}
		if($this->conn)
		{
			if($result = mysql_query($sql, $this->conn)) 
			{
				if(!$this->query_num)
				{
					$this->start_time = microtime(1);
				}
				$this->query_num = $this->query_num + 1;
				$this->query_sql[$this->query_num] = $sql;
				$this->query_run_time[$this->query_num] = $this->get_run_time(); 
				$this->query_runtime[$this->query_num] = $this->query_run_time[$this->query_num]- $this->query_run_time[$this->query_num - 1];
				return $result;
			}
			else
			{
				$this->print_err(mysql_error());
			}
		}
	}
	function fetch_array($result,$result_type = MYSQL_BOTH)
	{
		return mysql_fetch_array($result,$result_type);
	}
	/**
	 * @取一个字段值
	 * */
    function getOne($sql, $limited = false)
    {
        if ($limited == true)
        {
            $sql = trim($sql . ' LIMIT 1');
        }

        $res = $this->query($sql);
        if ($res !== false)
        {
            $row = mysql_fetch_row($res);

            if ($row !== false)
            {
                return $row[0];
            }
            else
            {
                return '';
            }
        }
        else
        {
            return false;
        }
    }
	/**
	 * @返回一条记录
	 * @
	*/
	function getOneRs($sql)
	{
        $res = $this->query($sql);
        if ($res !== false)
        {
            $row = mysql_fetch_assoc($res);

            if ($row !== false)
            {
                return $row;
            }
            else
            {
                return '';
            }
        }
        else
        {
            return false;
        }
	}
	/**
	 * @返回多条记录
	 * @
	*/
	function getAll($sql)
    {
        $res = $this->query($sql);
        if ($res !== false)
        {
            $arr = array();
            while ($row = mysql_fetch_assoc($res))
            {
                $arr[] = $row;
            }

            return $arr;
        }
        else
        {
            return false;
        }
    }
	
	function close()
	{
		if($this->conn)
		{
			return mysql_close($this->conn);
		}
	}
	
	function __destruct()
	{
		if($this->conn)
		{
			$this->close();
		}
	}
	function print_err($err)
	{
		if($this->is_debug)
		{
			die($err);
		}
	}
	function insert_id()
	{
		return mysql_insert_id($this->conn);
	}
	function get_query_num()
	{
		return $this->query_num;
	}
	function get_run_time()
	{
		return microtime(1) - $this->start_time;
	}
	function num_rows($result)
	{
		return mysql_num_rows($result);
	}
	
	/**
	 * 插入数据库
	 * @param string $table 表名
	 * @param array $arr 键名为字段名，键值为字段值
	 * @return integer 最后插入记录的ID
	 * */
	public function insert($table, $arr) {
		
		$filed = implode( "`,`", array_keys( $arr ) );
		$value = implode( "','", array_values( $arr ) );
		
		$sql = "INSERT INTO `{$table}` (`{$filed}` ) VALUES( '{$value}' )";
		$this->query ( $sql );
		$ret = $this->insert_id ( $this->conn );
		return $ret;
	}
	
	/**
	 * 更新数据库
	 * @param string $table 表名
	 * @param array $arr 键名为字段名，键值为字段值
	 * @param string $where 更新条件
	 * @param boolean
	 * */
	public function update($table, $arr, $where) {
		if( !$where ) return 'no value for where!';
		$str = $commat = '';
		foreach ( $arr as $k => $v ) {
			$str .= $commat ."`". $k . "`='" .$v. "'";
			$commat = ',';
		}
		$sql = "UPDATE `{$table}` SET {$str} WHERE {$where}";
		return $this->query ( $sql );
	}
	
	/**
	 * 删除数据
	 * @param string $table 表名
	 * @param string $where 删除条件
	 * @return boolean
	 * */
	public function delete($table, $where) {
		$sql = "DELETE FROM `{$table}` WHERE {$where}";
		return $this->query ( $sql );
	}
	
	/**
	 * 获得总记录数
	 * @param string $table 表名
	 * @param string $where 条件
	 * @param string $sql 特殊情况下用此sql
	 * @param integer
	 * */
	public function getCount($table, $where = "", $sql = "") {
		if( $where ) $where = " WHERE {$where}";
		if( empty ( $sql ) ) $sql = "SELECT COUNT(1) num FROM `{$table}` {$where}";
		$ret = $this->getOne( $sql );
		return $ret ['num'];
	}
	
	/**
	 * 在使用SQL_CALC_FOUND_ROWS 后调用，取得无limit限制的记录数
	 * */
	public function getNum(){
		$ret = mysql_fetch_assoc( $this->query("SELECT FOUND_ROWS() num") );
		return $ret['num'];
	}
	
}	
?>